package gestores;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sistema.Aposta;

public class GestorApostas extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet GestorApostas</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet GestorApostas at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void inserirAposta(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        if (dadosValidos(request)) {
            Hashtable<String, Object> dados_da_aposta = tabelaAposta(request);
            try {
                Aposta.insereAposta(dados_da_aposta);
            } catch (Exception ex) {
                //mandar erros
                //reencaminhar para pagina de erro
            }
            //reencaminhar para pagina de sucesso
            //  response.sendRedirect("/RHPlus/Gestor?gestor=gestor_de_utentes&accao=visualizar_cliente&id=" + id_pessoa);
        } else {
            //dá erro
            //session.setAttribute("erros", devolveTabelaDeErrosParaInserirDoencaGenerica(request));
        }
    }

    public Hashtable tabelaAposta(HttpServletRequest request) {

        Hashtable<String, String> tabelaAposta = new Hashtable<String, String>();
        tabelaAposta.put("var_escolha", request.getParameter("escolha"));
        tabelaAposta.put("var_odd", request.getParameter("odd"));
        tabelaAposta.put("var_stake", request.getParameter("stake"));
        tabelaAposta.put("var_estado", "activa");
        tabelaAposta.put("var_id_evento", request.getParameter("id_evento"));
        tabelaAposta.put("var_idutilizador", request.getParameter("id_utilizador"));

        return tabelaAposta;
    }

    private boolean dadosValidos(HttpServletRequest request) {

        if ((Long) request.getSession(false).getAttribute("id_utilizador") == null) {
            return true;
        }
        return false;

    }

    //visualiza todas as apostas, pelo seu estado
    public void visualizaApostas(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        try {

            String sub_accao = (String) request.getParameter("sub_accao");

            //Todas as apostas registadas
            if (sub_accao != null && sub_accao.equals("todas")) {

                session.setAttribute("lista_apostas", Aposta.devolveTodasApostas());
                response.sendRedirect("/Projecto_PR/mostra_apostas_apostas.jsp");
                // Todas as apostas que estão abertas

            } else if (sub_accao != null && sub_accao.equals("activas")) {

                session.setAttribute("lista_activas", Aposta.devolveAposta("activa"));
                response.sendRedirect("/Projecto_PR/mostra_apostas_abertas.jsp");

                //todas as apostas que já acabaram
            } else if (sub_accao != null && sub_accao.equals("fechadas")) {

                session.setAttribute("lista_activas", Aposta.devolveAposta("concluida"));
                response.sendRedirect("/Projecto_PR/mostra_apostas_fechadas.jsp");
            }
        } catch (SQLException ex) {
            Logger.getLogger(GestorApostas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GestorApostas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(GestorApostas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(GestorApostas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(GestorApostas.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
